package com.example.edu.Filter;

import com.example.edu.Utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去除 "Bearer " 部分

            try {
                // 检查令牌是否过期
                if (JwtUtil.isTokenExpired(token)) {
                    // 如果令牌过期，返回 401 错误，并附带错误消息
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("{\"message\": \"Token expired, please log in again.\"}");
                    return;
                }
                // 如果令牌将要过期刷新令牌
                if(JwtUtil.isTokenWillExpired(token)) {
                    String username = JwtUtil.getUsername(token);
                    response.setHeader("new_token",JwtUtil.generateToken(username));
                }
            } catch (ExpiredJwtException e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"message\": \"Token expired, please log in again.\"}");
                return;
            }
        }

        chain.doFilter(request, response);
    }
}

